<?php
declare (strict_types = 1);

namespace thinkless\common;

use think\App;

/**
 * 控制器基础类
 */
abstract class BaseController
{
    /**
     * Request实例
     * @var \app\patch\Request
     */
    protected $request;

    /**
     * 应用实例
     * @var \app\Thinkless
     */
    protected $app;

    /**
     * 构造方法
     * @access public
     * @param  App  $app  应用对象
     */
    public function __construct(App $app) {
        $this->app     = $app;
        $this->request = $this->app->request;
        $this->_initialize();
    }
    
    public function _initialize() {}

    public function isApi() {
        // 用axios要加: axios.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest'
        return $this->request->isAjax();
    }

    /**
     * @param string $data
     * @return \think\response\Json
     */
    public function jSuccess($data = "", $message = '', $append=[]) {
        $res = array_merge([
            'data'=> $data, 
            'code'=> 0, 
            'message'=> $message
        ], $append);
        return json($res);
    }

    public function getClientIp() {
        return request()->ip();
    }

    public function getPageSize() {
        return input('page_size') ?? 10;
    }

    public function getQueryOrder() {
        $sort = '';
        if(input('sort')) {
            $sort = input('sort') . ' ';
            $sort .= input('order') ? input('order') : 'asc';
        }
        return $sort;
    }
}
